import {AllOWED_TYPE, CHUNK_SIZE, UPLOAD_INFO,API} from './config/config';

;((doc) => {
  const oProgess = doc.querySelector("#uploadProgress");
  const oUploader = doc.querySelector("#videoUploader");
  let oPloadInfo = doc.querySelector("#uploadInfo");
  const oBtn = doc.querySelector("#uploadBtn");

  let upLoadedSize = 0;//保存当前文件上传的文件的大小进度
  const init = () => {
    bindEvent();
  };

  function bindEvent() {
    oBtn.addEventListener('click', uploadVideo, false);
  }

  async function uploadVideo() {
    const {files: [file]} = oUploader
    // console.log(file)
    const {name, type, size} = file
    if (!file) {
      oPloadInfo.innerHTML = UPLOAD_INFO.NO_FILE
      return
    }
    if (!AllOWED_TYPE[file.type]) {
      oPloadInfo.innerHTML = UPLOAD_INFO['INVALID_TYPE']
      return;
    }
    let uploadeResult =null
    oProgess.max = size
    oPloadInfo = ""
    // 上传文件的名称要是唯一的,所以说上传的文件要进行更改文件名称
    const fileName = `${new Date().getTime()}_${name}`
    while (upLoadedSize < size) {
      const fileChunk = file.slice(upLoadedSize, upLoadedSize + CHUNK_SIZE);
      const formData = createFormData({
        name, type, size, fileName, upLoadedSize, file: fileChunk
      });
      try {
        uploadeResult  = await axios.post(API.UPLOAD_VIDEO, formData)
        console.log(uploadeResult)
      } catch (e) {
        oPloadInfo.innerHTML= `${UPLOAD_INFO['UPLOAD_FileStateErro']}(${e.message})`
        return;
      }
      upLoadedSize += fileChunk.size;
      oProgess.value = upLoadedSize
    }
    oPloadInfo.innerHTML = UPLOAD_INFO["UPLOAD_FILESTATESECCESS"]
    oUploader.value = null
  }

  function createFormData({name, type, size, fileName, upLoadedSize, file}) {
    const fd = new FormData();
    fd.append("name", name);
    fd.append('type',type);
    fd.append('size', size);
    fd.append('fileName', fileName);
    fd.append('upLoadedSize', upLoadedSize);
    fd.append('file', file);
    return fd;
  }

  init()
})(document);
